package yannan.voiplock4ble;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yongchun.library.view.ImageSelectorActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.base.UnLoggedBaseActivity;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.UserBean;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.task.LoginTask;
import yannan.voiplock4ble.utils.AnimUtils;
import yannan.voiplock4ble.utils.CommonUtils;
import yannan.voiplock4ble.utils.PhotoViewUtils;
import yannan.voiplock4ble.utils.PopShowUtils;
import yannan.voiplock4ble.utils.StringEncrypt;
import yannan.voiplock4ble.utils.ToastUtils;

/**
 * 注册页面
 */
@Content(R.layout.avctivity_register)
public class RegisterActivity extends UnLoggedBaseActivity {


    private final static int PHONE_PAGE = 0x001;
    private final static int PASSWORD_PAGE = 0x002;
    private final static int CONFIRM_PAGE = 0x004;
    private final static int NICKNAME_PAGE = 0x005;

    @Bind(R.id.img_back_bottom)
    ImageView imgBackBottom;
    @Bind(R.id.btn_next_phone_bottom)
    TextView btnNextPhoneBottom;
    @Bind(R.id.bottom_lin_three)
    LinearLayout bottomLinThree;
    @Bind(R.id.ic_register_phone)
    ImageView icRegisterPhone;
    @Bind(R.id.et_register_phone)
    EditText etRegisterPhone;
    @Bind(R.id.rel_register_phone)
    RelativeLayout relRegisterPhone;
    @Bind(R.id.tv_after_setting)
    TextView tvAfterSetting;
    @Bind(R.id.btn_next_nickname_bottom)
    TextView btnNextNicknameBottom;
    @Bind(R.id.img_register_head)
    ImageView imgRegisterHead;
    @Bind(R.id.tv_register_phone)
    TextView tvRegisterPhone;
    @Bind(R.id.ic_register_nickname)
    ImageView icRegisterNickname;
    @Bind(R.id.et_register_nickname)
    EditText etRegisterNickname;
    @Bind(R.id.rel_register_nickname)
    RelativeLayout relRegisterNickname;
    /**
     * 当前页
     */
    int currentPage = PHONE_PAGE;
    @Bind(R.id.line_register_phone)
    LinearLayout lineRegisterPhone;
    @Bind(R.id.line_bottom)
    LinearLayout lineBottom;
    @Bind(R.id.line_input_nickname)
    LinearLayout lineInputNickname;
    @Bind(R.id.img_register_bg)
    ImageView imgRegisterBg;
    private String verCode;
    private String registerPhone;
    private String passWord;
    private String imgHeadPath;
    private boolean isRegister;
    private String toastStr = "";

    @Override
    public void initData() {
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        relRegisterNickname.setVisibility(View.GONE);
        relRegisterPhone.setVisibility(View.VISIBLE);
        btnNextPhoneBottom.setText("验证手机号");
        etRegisterPhone.setHint("请输入手机号");
        etRegisterPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        etRegisterPhone.setTextColor(getResources().getColor(R.color.white));
        isRegister = getIntent().getBooleanExtra("isRegister", true);
        if (isRegister) {
            toastStr = "取消注册";
        } else {
            toastStr = "取消重置密码";
        }

    }

    @OnClick({R.id.img_back_bottom, R.id.tv_after_setting, R.id.btn_next_phone_bottom, R.id.btn_next_nickname_bottom, R.id.img_register_head})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_next_phone_bottom:
                doNext();
                break;
            case R.id.img_back_bottom:
                backUpPage();
                break;
            case R.id.btn_next_nickname_bottom:
                registerUser(etRegisterNickname.getText().toString().toString());
                break;
            case R.id.tv_after_setting:
                registerUser("");
                break;
            case R.id.img_register_head:
                PhotoViewUtils.startPicture(RegisterActivity.this);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            imgHeadPath = images.get(0).toString();
            PhotoViewUtils.upLoadHead(RegisterActivity.this, imgHeadPath, "", imgRegisterHead);
        }
    }

    /**
     * 返回键
     */
    private void backUpPage() {
        switch (currentPage) {
            case NICKNAME_PAGE:
            case PHONE_PAGE:
                PopShowUtils.showCommonDialog(RegisterActivity.this, "确定要" + toastStr + "吗？", "取消", "确定", true, new PopShowUtils.IDialogCommonListener() {
                    @Override
                    public void onClick(int dir) {
                        if (dir == PopShowUtils.COMMON_DIALOG_RIGHT)
                            RegisterActivity.this.finish();
                    }
                });
                break;
            case CONFIRM_PAGE:
                currentPage = PHONE_PAGE;
                verCode = "";
                icRegisterPhone.setImageDrawable(getResources().getDrawable(R.drawable.ic_head_white));
                btnNextPhoneBottom.setText("验证手机号");
                etRegisterPhone.setText("");
                etRegisterPhone.setHint("请输入手机号");
                etRegisterPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
                etRegisterPhone.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                AnimUtils.doAnimation(RegisterActivity.this, bottomLinThree, bottomLinThree);
                AnimUtils.doAnimation(RegisterActivity.this, lineRegisterPhone, lineRegisterPhone);
                break;
            case PASSWORD_PAGE:
                verCode = "";
                currentPage = PHONE_PAGE;
                etRegisterPhone.setText("");
                etRegisterPhone.setHint("请输入手机号");
                etRegisterPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
                etRegisterPhone.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                btnNextPhoneBottom.setText("验证手机号");
                icRegisterPhone.setImageDrawable(getResources().getDrawable(R.drawable.ic_head_white));
                AnimUtils.doAnimation(RegisterActivity.this, bottomLinThree, bottomLinThree);
                AnimUtils.doAnimation(RegisterActivity.this, lineRegisterPhone, lineRegisterPhone);
                break;
        }
    }

    private void doNext() {
        switch (currentPage) {
            case PHONE_PAGE:
                doPhone();
                break;
            case CONFIRM_PAGE:
                doConfirm();
                break;
            case PASSWORD_PAGE:

                if (etRegisterPhone.getText().toString().trim() == null || etRegisterPhone.getText().toString().trim().equals("")) {
                    ToastUtils.showToast(RegisterActivity.this, "密码不能为空");
                    etRegisterPhone.requestFocus();
                    return;
                }
                passWord = etRegisterPhone.getText().toString().trim();
                btnNextPhoneBottom.setText("完成");
                if (isRegister) {
                    tvRegisterPhone.setText(registerPhone);
                    AnimUtils.doAnimation(RegisterActivity.this, relRegisterPhone, relRegisterNickname);
                    currentPage = NICKNAME_PAGE;
                } else {
                    btnNextPhoneBottom.setEnabled(false);
                    forgetPwd();
                }
                break;
        }
    }

    private void forgetPwd() {
        passWord = StringEncrypt.EncryptBySHA_256(passWord);
        NetUtils.getNetworkService().forgetPwd(registerPhone, passWord)
                .enqueue(new NetworkCallBack<CommonResponse>() {
                    @Override
                    public void onSuc(CommonResponse resBody) {
                        btnNextPhoneBottom.setEnabled(true);
                        ToastUtils.showToast(RegisterActivity.this, "重置成功");
                        finish();
                    }

                    @Override
                    public void onFail(String msg) {
                        btnNextPhoneBottom.setEnabled(true);
                        ToastUtils.showToast(RegisterActivity.this, "重置失败");
                    }
                });
    }

    private void doConfirm() {
        if (!etRegisterPhone.getText().toString().trim().equals(verCode)) {
            ToastUtils.showToast(mContext, "验证码不正确");

            etRegisterPhone.requestFocus();
            return;
        }
        etRegisterPhone.setText("");
        etRegisterPhone.setHint("请输入密码");
        btnNextPhoneBottom.setText("完成");
        etRegisterPhone.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        etRegisterPhone.setTransformationMethod(PasswordTransformationMethod.getInstance());
        icRegisterPhone.setImageDrawable(getResources().getDrawable(R.drawable.ic_input));
        currentPage = PASSWORD_PAGE;
        AnimUtils.doAnimation(RegisterActivity.this, bottomLinThree, bottomLinThree);
        AnimUtils.doAnimation(RegisterActivity.this, lineRegisterPhone, lineRegisterPhone);
    }

    private void doPhone() {
        if (etRegisterPhone.getText().toString().trim() == null || etRegisterPhone.getText().toString().trim().equals("")) {
            etRegisterPhone.requestFocus();
            ToastUtils.showToast(RegisterActivity.this, "请输入手机号");
            return;
        } else if (!CommonUtils.validPhone(etRegisterPhone.getText().toString().trim())) {
            ToastUtils.showToast(RegisterActivity.this, "请输入正确的手机号");
            return;
        }
        registerPhone = etRegisterPhone.getText().toString().trim();
        getVerCode(etRegisterPhone.getText().toString().trim());

    }

    /**
     * 获取验证码
     */
    private void getVerCode(String phoneNumber) {
        int type = 1;
        if (isRegister) {
            type = 1;
        } else {
            type = 2;
        }
        btnNextPhoneBottom.setEnabled(false);
        NetUtils.getNetworkService().getVerificationCode(type + "", phoneNumber)
                .enqueue(new NetworkCallBack<CommonResponse>() {
                    @Override
                    public void onSuc(CommonResponse resBody) {
                        if (resBody != null) {
                            verCode = resBody.returnValue;
                            if (!verCode.equals("该手机号已注册")) {
                                icRegisterPhone.setImageDrawable(getResources().getDrawable(R.drawable.three_point));
                                etRegisterPhone.setText("");
                                etRegisterPhone.setHint("请输入验证码");
                                btnNextPhoneBottom.setText("设置密码");
                                currentPage = CONFIRM_PAGE;
                                AnimUtils.doAnimation(RegisterActivity.this, bottomLinThree, bottomLinThree);
                                AnimUtils.doAnimation(RegisterActivity.this, lineRegisterPhone, lineRegisterPhone);
                                if (BuildConfig.DEBUG)
                                    Log.e("LoginActivity", "verCode:" + verCode);
                            } else {
                                ToastUtils.showToast(mContext, verCode);
                            }
                        } else {
                            ToastUtils.showToast(mContext, "获取验证码失败");
                        }
                        btnNextPhoneBottom.setEnabled(true);
                    }

                    @Override
                    public void onFail(String msg) {
                        ToastUtils.showToast(mContext, "获取验证码失败");
                        btnNextPhoneBottom.setEnabled(true);
                    }
                });
    }

    /**
     * 注册用户
     */
    private void registerUser(String nickName) {
        showProgress();
        passWord = StringEncrypt.EncryptBySHA_256(passWord);
        NetUtils.getNetworkService().registerUser(registerPhone, passWord, 1, PhotoViewUtils.getHeadUrl(), nickName)
                .enqueue(new NetworkCallBack<UserBean>() {
                    @Override
                    public void onSuc(UserBean resBody) {
                        if (resBody != null) {
                            MyApplication.getInterface().userBean = resBody;
                            LoginTask.create(RegisterActivity.this, registerPhone, passWord, true, false).start();
                            ToastUtils.showToast(mContext, "注册成功");
                        } else {
                            dimssProgress();
                            ToastUtils.showToast(mContext, "注册失败");
                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        dimssProgress();
                        ToastUtils.showToast(mContext, "注册失败");
                    }
                });
    }

    @Override
    public void onBackPressed() {
        backUpPage();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Object msg) {
        if (msg instanceof String) {
            if (msg.equals("closeLoginActivity"))
                finish();
        }
    }

}
